package com.ruoyi.sms.service.impl;

import com.alibaba.fastjson2.JSON;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.sms.config.SmsConfig;
import com.ruoyi.sms.service.SmsService;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 短信服务实现类
 */
@Service
public class SmsServiceImpl implements SmsService {
    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Autowired
    private SmsConfig smsConfig;

    @Override
    public AjaxResult sendSms(String phoneNumbers, Map<String, String> templateParam) {
        if (StringUtils.isEmpty(phoneNumbers)) {
            return AjaxResult.error("手机号码不能为空");
        }

        try {
            // 配置凭证
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(smsConfig.getAccessKeyId())
                    .accessKeySecret(smsConfig.getAccessKeySecret())
                    .build());

            // 创建异步客户端
            AsyncClient client = AsyncClient.builder()
                    .region("cn-hangzhou")
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride("dysmsapi.aliyuncs.com")
                    )
                    .build();

            // 创建请求对象
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(smsConfig.getSignName())
                    .templateCode(smsConfig.getTemplateCode())
                    .phoneNumbers(phoneNumbers)
                    .templateParam(JSON.toJSONString(templateParam))
                    .build();

            // 发送短信
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();

            // 关闭客户端
            client.close();

            if ("OK".equals(resp.getBody().getCode())) {
                return AjaxResult.success("短信发送成功");
            } else {
                return AjaxResult.error("短信发送失败：" + resp.getBody().getMessage());
            }
        } catch (Exception e) {
            log.error("短信发送异常", e);
            return AjaxResult.error("短信发送异常：" + e.getMessage());
        }
    }

    @Override
    public AjaxResult sendVerificationCode(String phoneNumber, String code) {
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("code", code);
        return sendSms(phoneNumber, templateParam);
    }
} 